package org.dromara.basic.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import org.dromara.basic.domain.TeachClass;
import org.dromara.basic.domain.vo.TeachClassVo;
import org.dromara.common.core.domain.model.LoginUser;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.service.MemberService;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.run.domain.Schedule;
import org.dromara.utils.FileUploadUtils;
import org.springframework.stereotype.Service;
import org.dromara.basic.domain.bo.MemberBo;
import org.dromara.basic.domain.vo.MemberVo;
import org.dromara.basic.domain.Member;
import org.dromara.basic.mapper.MemberMapper;
import org.dromara.basic.service.IMemberService;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * 成员信息表Service业务层处理
 *
 * @author chl
 * @date 2024-08-19
 */
@RequiredArgsConstructor
@Service
public class MemberServiceImpl implements IMemberService, MemberService {

    private final MemberMapper baseMapper;

    /**
     * 查询成员信息表
     */
    @Override
    public MemberVo queryById(Long memberId){
        MemberBo memberBo=new MemberBo();
        memberBo.setMemberId(memberId);
        QueryWrapper<Member> lqw = buildQueryWrapper(memberBo);

        return baseMapper.selectMemberVO(lqw);
    }

    /**
     * 查询成员信息表列表
     */
    @Override
    public TableDataInfo<MemberVo> queryPageList(MemberBo bo, PageQuery pageQuery) {
        QueryWrapper<Member> lqw = buildQueryWrapper(bo);
        Page<MemberVo> result = baseMapper.selectMemberList(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询成员信息表列表
     */
    @Override
    public List<MemberVo> queryList(MemberBo bo) {
        QueryWrapper<Member> lqw = buildQueryWrapper(bo);
        return baseMapper.selectMemberList(lqw);
    }

    @Override
    public MemberVo queryVo(MemberBo bo) {
        QueryWrapper<Member> lqw = buildQueryWrapper(bo);

        return baseMapper.selectMemberVO(lqw);
    }

    @Override
    public MemberVo queryByIdNumber(String idNumber,String tenantId) {
        MemberVo memberVo = baseMapper.selectVoOne(
            new LambdaQueryWrapper<Member>()
            .eq(Member::getIdNumber, idNumber)
            .eq(Member::getTenantId, tenantId)
        );
        return memberVo;
    }
    @Override
    public MemberVo queryByIdNumber(String idNumber) {
        MemberVo memberVo = baseMapper.selectVoOne(
            new LambdaQueryWrapper<Member>()
                .eq(Member::getIdNumber, idNumber)
        );
        return memberVo;
    }
    @Override
    public MemberVo queryByStudentName(String studentName) {
        MemberVo memberVo = baseMapper.selectVoOne(
            new LambdaQueryWrapper<Member>()
                .eq(StringUtils.isNotEmpty(studentName),Member::getName, studentName)
        );
        return memberVo;
    }

    private QueryWrapper<Member> buildQueryWrapper(MemberBo bo) {
        Map<String, Object> params = bo.getParams();
        QueryWrapper<Member> lqw = new QueryWrapper<>();
        lqw.eq(StringUtils.isNotBlank(bo.getIdNumber()), "pmi.id_number", bo.getIdNumber());
        lqw.eq(bo.getMemberId()!=null, "pmi.member_id", bo.getMemberId());
        lqw.eq(StringUtils.isNotBlank(bo.getTenantId()), "pmi.tenant_id", bo.getTenantId());
        lqw.like(StringUtils.isNotBlank(bo.getName()), "pmi.name", bo.getName());
        lqw.eq(StringUtils.isNotBlank(bo.getGender()), "pmi.gender", bo.getGender());
        lqw.eq(StringUtils.isNotBlank(bo.getPhoneNumber()), "pmi.phone_number", bo.getPhoneNumber());
        lqw.eq(StringUtils.isNotBlank(bo.getIdCardNumber()), "pmi.id_card_number", bo.getIdCardNumber());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), "pmi.status", bo.getStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getCollegeId()), "sd2.dept_id", bo.getCollegeId());
        lqw.eq(StringUtils.isNotBlank(bo.getGrade()), "pbtc.grade", bo.getGrade());
        lqw.eq(bo.getClassId()!=null, "pmi.class_id", bo.getClassId());
        lqw.eq(StringUtils.isNotBlank(bo.getProfessionalId()), "sd1.dept_id", bo.getProfessionalId());
        lqw.in(CollectionUtils.isNotEmpty(bo.getClassIdList()),"pmi.class_id",bo.getClassIdList());
        lqw.in(CollectionUtils.isNotEmpty(bo.getCollegeList()),"sd2.dept_id",bo.getCollegeList());
        lqw.in(CollectionUtils.isNotEmpty(bo.getYearsList()),"pmi.years",bo.getYearsList());
        lqw.eq(StringUtils.isNotBlank(bo.getYears()), "pmi.years", bo.getYears());
        return lqw;
    }

    /**
     * 新增成员信息表
     */
    @Override
    public Boolean insertByBo(MemberBo bo,Boolean isValid) {
        Member add = MapstructUtils.convert(bo, Member.class);
        if(isValid){
            validEntityBeforeSave(add);
        }
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setMemberId(add.getMemberId());
        }
        return flag;
    }

    /**
     * 修改成员信息表
     */
    @Override
    public Boolean updateByBo(MemberBo bo,Boolean isValid) {
        Member update = MapstructUtils.convert(bo, Member.class);
        if(isValid){
            validEntityBeforeSave(update);
        }

        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(Member entity){
        QueryWrapper<Member> queryWrapper=new QueryWrapper();
        queryWrapper.eq("id_number",entity.getIdNumber());
        if(entity.getMemberId()!=null){
            queryWrapper.ne("member_id",entity.getMemberId());
        }
        List<MemberVo> memberVos = baseMapper.selectVoList(queryWrapper);
        if (!CollectionUtils.isEmpty(memberVos)) {
            if(StringUtils.isNotEmpty(entity.getFaceImage())){
                List<String> urls = Arrays.stream(entity.getFaceImage().split(",")).collect(Collectors.toList());
                for (String url:urls) {
                    FileUploadUtils.delFile(url);
                }
            }
            throw new ServiceException("学生信息重复添加");
        }
    }

    /**
     * 批量删除成员信息表
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public String selectMemberNameByIdNumber(String idNumber) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        Member member = baseMapper.selectOne(new LambdaQueryWrapper<Member>()
            .select(Member::getName).eq(Member::getIdNumber, idNumber).eq(Member::getTenantId,loginUser.getTenantId()));
        return ObjectUtil.isNull(member) ? null : member.getName();
    }
}
